package com.itheima.reggie.config;


import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.time.LocalDateTime;


@Component
@Aspect
@Slf4j
public class UpdateAspect {

    @Autowired
    HttpServletRequest req;
    @Pointcut("execution(* com.itheima.reggie..*_aop(..))")
    private void pt(){}

    @Around("pt()")
    public R method(ProceedingJoinPoint jp){
        Long employee = (Long) req.getSession().getAttribute("employee");
        LocalDateTime now = LocalDateTime.now();
        Object[] args = jp.getArgs();
        Class<?> aClass = args[0].getClass();


        log.info(args[0].toString());
        log.info(req.getRequestURI());

        Field createTime=null;
        Field updateTime=null;
        Field createUser=null;
        Field updateUser=null;
        R<String> r=null;
        try {
            if ((createTime = aClass.getDeclaredField("createTime")) != null) {
                createTime.setAccessible(true);
                createTime.set(args[0], now);
            }
            if ((updateTime = aClass.getDeclaredField("updateTime")) != null) {
                updateTime.setAccessible(true);
                updateTime.set(args[0], now);
            }
            if ((createUser = aClass.getDeclaredField("createUser")) != null) {
                createUser.setAccessible(true);
                createUser.set(args[0], employee);
            }
            if ((updateUser = aClass.getDeclaredField("updateUser")) != null) {
                updateUser.setAccessible(true);
                updateUser.set(args[0], employee);
            }
            r= (R) jp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        log.info("{}",r);
        return r;
    }
}
